import struct

# 定义常量
START_FRAME = 0xABCD

def speed_to_hex(left_speed, right_speed):
    """
    将左右轮速度值转换为协议格式的十六进制字符串
    
    参数:
    left_speed (int): 左轮速度值 (-32768 到 32767)
    right_speed (int): 右轮速度值 (-32768 到 32767)
    
    返回:
    str: 十六进制字符串，每个字节用空格分隔
    """
    # 确保速度值在有效范围内
    left_speed = max(min(left_speed, 32767), -32768)
    right_speed = max(min(right_speed, 32767), -32768)
    
    # 计算校验和
    checksum = START_FRAME ^ right_speed ^ left_speed
    checksum &= 0xFFFF  # 确保在0-65535范围内
    
    # 打包数据为二进制格式
    packed_data = struct.pack('<HhhH',
                             START_FRAME,
                             right_speed,
                             left_speed,
                             checksum)
    
    # 转换为十六进制字符串（大写，空格分隔）
    hex_str = ' '.join([f"{b:02X}" for b in packed_data])
    return hex_str

def speed_to_bytes(left_speed, right_speed):
    """
    将左右轮速度值转换为协议格式的字节数组
    
    参数:
    left_speed (int): 左轮速度值 (-32768 到 32767)
    right_speed (int): 右轮速度值 (-32768 到 32767)
    
    返回:
    bytes: 协议格式的字节数组
    """
    # 确保速度值在有效范围内
    left_speed = max(min(left_speed, 32767), -32768)
    right_speed = max(min(right_speed, 32767), -32768)
    
    # 计算校验和
    checksum = START_FRAME ^ right_speed ^ left_speed
    checksum &= 0xFFFF  # 确保在0-65535范围内
    
    # 打包数据为二进制格式
    return struct.pack('<HhhH',
                      START_FRAME,
                      right_speed,
                      left_speed,
                      checksum)

def print_speed_command(left_speed, right_speed):
    """
    打印速度命令的十六进制表示
    
    参数:
    left_speed (int): 左轮速度值
    right_speed (int): 右轮速度值
    """
    hex_str = speed_to_hex(left_speed, right_speed)
    print(f"速度命令: 左轮={left_speed}, 右轮={right_speed}")
    print(f"十六进制: {hex_str}")
    print(f"字节序列: {speed_to_bytes(left_speed, right_speed)}")
    print()

# 测试示例
if __name__ == "__main__":
    # 示例1: 左轮100, 右轮-100
    print_speed_command(100, -100)
    # 示例4: 自定义速度
    left = int(input("请输入左轮速度: ") or 0)
    right = int(input("请输入右轮速度: ") or 0)
    print_speed_command(left, right)